package com.example.carbonalgorithm.common.util;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jqllxew
 * 2019/8/13
 */
public class StringUtil {

    public static boolean isEmpty(Object obj) {
        return obj == null || "".equals(obj) || "null".equals(obj) || "undefined".equals(obj);
    }

    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }


    public static byte[] inputStream2byte(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int i;
        while ((i = in.read(bytes)) != -1) {
            out.write(bytes, 0, i);
        }
        out.flush();
        out.close();
        return out.toByteArray();
    }

    public static String inputStream2string(InputStream in) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
        //最好在将字节流转换为字符流的时候 进行转码
        StringBuilder buffer = new StringBuilder();
        String line = "";
        while ((line = bf.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }

    public static String get32UUID() {
        return UUID.randomUUID().toString().trim().replaceAll("-", "");
    }

    public static String get16UUID() {
        return get32UUID().substring(16);
    }

    public static String getSHA1(String inStr) {
        return bytesToString(inStr.getBytes(StandardCharsets.UTF_8), "SHA-1");
    }

    public static String getSHA256(String inStr) {
        return bytesToString(inStr.getBytes(StandardCharsets.UTF_8), "SHA-256");
    }

    public static String getMD5(String inStr) {
        return bytesToString(inStr.getBytes(StandardCharsets.UTF_8), "MD5");
    }

    public static String bytesToString(byte[] bytes, String algorithm) {
        StringBuilder buf = new StringBuilder();
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(algorithm);
            mdTemp.update(bytes);
            byte[] md = mdTemp.digest();
            for (byte b : md) {
                int i = b & 0xff;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    public static String[] getStart2End(int s) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        Date time = calendar.getTime();
        calendar.set(Calendar.MILLISECOND, calendar.get(Calendar.MILLISECOND) + s);
        Date time1 = calendar.getTime();
        String format = sf.format(time);
        String format1 = sf.format(time1);
        String[] sr = new String[2];
        sr[0] = format;
        sr[1] = format1;
        return sr;
    }

    public static String createNonceStr(int length) {
        StringBuilder sb = new StringBuilder();
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random rd = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(rd.nextInt(chars.length() - 1)));
        }
        return sb.toString();
    }

    public static String nowStr() {
        SimpleDateFormat sf = new SimpleDateFormat("yyMMddHHmmssSSS");
        return sf.format(new Date());
    }

    public static String join(Collection<String> coll, String joinStr) {
        Iterator<String> iterator = coll.iterator();
        int i = 0;
        StringBuilder sb = new StringBuilder();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (i > 0)
                sb.append(joinStr).append(next);
            else
                sb.append(next);
            i++;
        }
        return sb.toString();
    }

    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    public static void returnXml(HttpServletResponse response, String xml) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/xml;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(xml);
        out.close();
    }

    public static boolean isWindows() {
        String osName = System.getProperty("os.name");
        return osName.startsWith("Windows");
    }

    /**
     * 判断字段是否相同
     *
     * @param p1 现输入字段
     * @param p2 已保存字段
     * @return p1, p2 为空 p1=p2 true  p1!=p2 false
     */
    public static boolean isequals(String p1, String p2) {
        if (p1 != null && p2 != null && !p1.equals(p2))
            return false;
        return true;
    }

    /**
     * 判断字段中是否有某个数据
     *
     * @param str
     * @param findstr
     * @return
     */
    public static boolean isfind(String str, String findstr) {
        if (str.indexOf(findstr) > 0)
            return true;
        else
            return false;
    }

    /**
     * 判断字符串是否为纯数字
     *
     * @param str
     * @return
     */
    public static boolean isNum(String str) {
        Pattern compile = Pattern.compile("[0-9]+");
//        Pattern compile = Pattern.compile("[a-zA-Z]+");
//        Pattern compile = Pattern.compile("[[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\\n|\\r|\\t]+");
        Matcher matcher = compile.matcher(str);
        boolean b = matcher.matches();
        return b;
    }

    /**
     * 判断字符串是否有数字
     *
     * @param str
     * @return
     */
    public static boolean findNum(String str) {
        return findStr(str, "[0-9]+");
    }

    /**
     * 判断字符串是否有数字
     *
     * @param str
     * @return
     */
    public static boolean findEnglish(String str) {
        return findStr(str, "[a-zA-Z]+");
    }

    /**
     * 判断字符串是否有数字
     *
     * @param str
     * @return
     */
    public static boolean findSpecial(String str) {
        return findStr(str, "[[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\\n|\\r|\\t]+");
    }

    /**
     * 判断是否含中文
     *
     * @param str
     * @return
     */
    public static boolean findChinese(String str) {
        return findStr(str, ".*[\\u4e00-\\u9fa5].*");
    }

    /**
     * 判断传入字符串中是否包含某种字符
     *
     * @param str     传入字符
     * @param pattern 正则表达式
     * @return 包含 true 不包含 false
     */
    public static boolean findStr(String str, String pattern) {
        Pattern compile = Pattern.compile(pattern);
        Matcher matcher = compile.matcher(str);
        return matcher.find();
    }

}
